package com.crop.back.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 定义一个 MD5 工具类，用于密码加密
 */
public class MD5Util {
    public static String encryptMD5(String strSrc) {
        try {
            char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                    '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            byte[] bytes = strSrc.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            bytes = md.digest();
            int j = bytes.length;
            char[] chars = new char[j * 2];
            int k = 0;
            for (int i = 0; i < bytes.length; i++) {
                byte b = bytes[i];
                chars[k++] = hexChars[b >>> 4 & 0xf];
                chars[k++] = hexChars[b & 0xf];
            }
            return new String(chars);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5加密出错！！+" + e);
        }
    }

    public static final int offset = Integer.MIN_VALUE + 10086;

    // 加密
    public static String encrypt(String s) {

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < s.length(); i++) {
            sb.append("" + (char)(((int)s.charAt(i)) + offset));
        }

        return new StringBuilder(Base64.getEncoder().encodeToString(new String(sb.toString()).getBytes())).reverse().toString();
    }

    // 解密
    public static String decryt(String s) {

        s = new String(Base64.getDecoder().decode(new StringBuilder(s).reverse().toString()));

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < s.length(); i++) {
            sb.append((char)(((int)s.charAt(i)) - offset));
        }

        return sb.toString();
    }


}
